const { defineConfig } = require('@vue/cli-service')
const CompressionWebpackPlugin = require('compression-webpack-plugin')
const isProduction = process.env.NODE_ENV === 'production'

module.exports = defineConfig({
    transpileDependencies: true,
    // 禁用生产环境的sourceMap
    productionSourceMap: false,

    // 开发服务器配置
    devServer: {
        // 代理配置
        proxy: {
            // 当请求路径以/api开头时，将请求代理到目标服务器
            '/api': {
                target: 'https://www.banfuxiong.com/api', // 后端服务器地址，根据实际情况修改
                // target: 'http://localhost:8069', // 后端服务器地址，根据实际情况修改
                changeOrigin: true, // 允许跨域
                pathRewrite: {
                    '^/api': '' // 路径重写，将/api前缀去掉
                }
            }
        }
    },

    configureWebpack: config => {
        if (isProduction) {
            // 启用gzip压缩 - 修改配置以兼容当前版本
            config.plugins.push(
                new CompressionWebpackPlugin({
                    filename: '[path][base].gz',
                    algorithm: 'gzip',
                    test: /\.js$|\.css$|\.html$/,
                    threshold: 10240,
                    minRatio: 0.8
                })
            )

            // 优化代码分割配置
            config.optimization = {
                splitChunks: {
                    chunks: 'all',
                    maxInitialRequests: Infinity,
                    minSize: 20000,
                    cacheGroups: {
                        elementUI: {
                            name: 'chunk-elementUI',
                            test: /[\\/]node_modules[\\/]element-ui[\\/]/,
                            priority: 30
                        },
                        axios: {
                            name: 'chunk-axios',
                            test: /[\\/]node_modules[\\/]axios[\\/]/,
                            priority: 20
                        },
                        vue: {
                            name: 'chunk-vue',
                            test: /[\\/]node_modules[\\/](vue|vue-router)[\\/]/,
                            priority: 25
                        },
                        commons: {
                            name: 'chunk-commons',
                            minChunks: 2,
                            priority: 10,
                            reuseExistingChunk: true
                        },
                        vendors: {
                            name: 'chunk-vendors',
                            test: /[\\/]node_modules[\\/]/,
                            priority: 5
                        }
                    }
                }
            }
        }
    },

    chainWebpack: config => {
        // 移除prefetch插件
        config.plugins.delete('prefetch')

        if (isProduction) {
            // 移除moment.js语言包
            config.plugin('ignore')
                .use(require('webpack').IgnorePlugin, [{ resourceRegExp: /^\.\/locale$/, contextRegExp: /moment$/ }])
        }
    }
})
